﻿namespace YidanSoft.Library.EditorUtility.WinControls
{
    using System;
    using System.Drawing;
    using System.Windows.Forms;
    using YidanSoft.Library.EditorUtility.General;
    using YidanSoft.Library.EditorUtility.Win32;

    internal class ColorPickerEditCtrlHook : NativeWindow
    {
        private ColorPicker colorPicker;
        private bool ignoreNextPaintMessage = false;

        public ColorPickerEditCtrlHook(ColorPicker colorPicker)
        {
            this.colorPicker = colorPicker;
        }

        private void DrawDisableState()
        {
            using (Graphics graphics = Graphics.FromHwnd(base.Handle))
            {
                STRINGBUFFER stringbuffer;
                YidanSoft.Library.EditorUtility.Win32.RECT rc = new YidanSoft.Library.EditorUtility.Win32.RECT();
                WindowsAPI.GetClientRect(base.Handle, ref rc);
                Rectangle rect = new Rectangle(rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top);
                graphics.FillRectangle(Brushes.White, rect);
                WindowsAPI.GetWindowText(base.Handle, out stringbuffer, 0x200);
                using (Brush brush = new SolidBrush(SystemColors.ControlDark))
                {
                    string szText = stringbuffer.szText;
                    Size size = TextUtil.GetTextSize(graphics, szText, SystemInformation.MenuFont);
                    Point point = new Point(rc.left, rc.top + ((rc.bottom - size.Height) / 2));
                    graphics.DrawString(szText, this.colorPicker.Font, brush, (PointF) point);
                }
            }
        }

        protected override void WndProc(ref Message m)
        {
            Msg msg = (Msg) m.Msg;
            if (m.Msg == 15)
            {
                if (this.ignoreNextPaintMessage)
                {
                    this.ignoreNextPaintMessage = false;
                    return;
                }
                if (!this.colorPicker.Enabled)
                {
                    base.WndProc(ref m);
                    this.ignoreNextPaintMessage = true;
                    this.DrawDisableState();
                    return;
                }
            }
            base.WndProc(ref m);
        }
    }
}

